// 帖子和二手可以共用这个评论
import mongoose from 'mongoose';
import moment from 'moment';
import db from './db';
mongoose.Promise = global.Promise;

const PostJoinSchema = new mongoose.Schema({
    content: String, // 投票内容或者参与活动内容
    postId: String, // 帖子id
    creatorId: String,
    creator: Object,
    createTime: Number,
});

PostJoinSchema.methods.savePostJoin = function (postJoin, cb) {
    postJoin.createTime = moment().unix();
    this.model('postJoin').insertMany([postJoin], cb);
};

PostJoinSchema.methods.getPostJoins = function (query, cb) {
    const { current, pageSize, ...leftQuery } = query;
    const postJoinModel = this.model('postJoin');
    postJoinModel.count(leftQuery, function (err, count) {
        const hasMore = count / pageSize > current;
        postJoinModel.find(leftQuery).sort({createTime: -1}).skip((current - 1) * pageSize).limit(pageSize).exec((err, postJoins) => cb(err, postJoins, count, hasMore));
    });
};

PostJoinSchema.methods.getAllPostJoins = function (query, cb) {
    this.model('postJoin').find(query, { name: 1, _id: 0 }, cb);
};

PostJoinSchema.methods.getPostJoin = function (query, cb) {
    this.model('postJoin').findOne(query, cb);
};

PostJoinSchema.methods.updatePostJoin = function (postJoin, cb) {
    const _id = postJoin._id;
    delete postJoin._id;
    this.model('postJoin').findOneAndUpdate({ _id }, { $set: postJoin }, cb);
};

PostJoinSchema.methods.removePostJoins = function (postJoinIds, cb) {
    this.model('postJoin').remove({ _id: { $in: postJoinIds } }, cb);
};

export default db.model('postJoin', PostJoinSchema);